<!--
@fucntion: 用户信息管理
-->
<template>
<div class="components-system-user">
  <el-row>
    <el-col>
      <table-panel :name="'用户信息'" :columns="userColumns" :tableData="userData" :height="665" :showRowNumber="true" :multiSelection="true"
      :canCreate="authorities.create" :canEdit="authorities.edit" :canDelete="authorities.delete"
      :currentPage="userCurrentPage" :totalNum="userTotalNum" @page-change="onPageChange('user',$event)" :pageSize="pageSize"
      @table-searching="onSearching('user',$event)"
      @table-create="onCreate('user',$event)" @table-edit="onEdit('user', $event)"
      @table-delete="onDelete('user',$event)" @table-export="onExport('user',$event)"
      @selection-change="onSelectionChange('user',$event)"></table-panel>
    </el-col>
    <el-dialog title="用户信息" width="40%" :visible.sync="userDlgVisible">
      <el-form ref="userForm" :model="userRecord" :rules="userRules"
      label-position="right" label-width="80px" size="mini" status-icon>
        <el-form-item label="人员类型" prop="sslx">
          <el-select v-model="userRecord.sslx" placeholder="请选择类型" @change="sslxChange">
            <template v-for="item in ['教师','学生']">
              <el-option :key="item" :label="item" :value="item"> </el-option>
            </template>
          </el-select>
        </el-form-item> 
        <el-form-item label="人员" prop="sslxbh">
          <el-select v-model="userRecord.sslxbh" placeholder="请选择人员" filterable remote 
          :remote-method="sslxbhSearching" :loading="sslxbhLoading">
            <template v-for="item in teacherAndStudentData">
              <el-option :key="item.sslxbh" :label="item.xm" :value="item.sslxbh">
                <span style="float: left">{{ item.xm }}</span>
                <span style="float: right; font-size: 13px; margin-left:5px;">{{ item.sslxbh }}</span>
              </el-option>
            </template>
          </el-select>
        </el-form-item> 
        <el-form-item label="用户名" prop="yhm">
          <el-input v-model="userRecord.yhm" :readonly="userRecord.sslxbh != ''"></el-input>
        </el-form-item>
        <el-checkbox v-model="userRecord.sfqy" label="是否启用" >
        </el-checkbox>
        <el-row>
          <el-button v-if="userRecord.zgbh !==''" @click="onResetPassword('user', $event)" type="warning" size="mini">重置密码</el-button>
          <el-button @click="onConfirm('user', $event)" type="primary" size="mini">确定</el-button>
          <el-button @click="userDlgVisible=false" size="mini">取消</el-button>
        </el-row>
      </el-form>
    </el-dialog>
  </el-row>
</div>
</template>
<script>
import TablePanel from "@/components/basic/TablePanel";
import {
  formModelInitFromTable,
  formRulesInitFromTable
} from "@/utils/formutils.js";
import {
  trueFalseRenderer
} from "@/utils/tableutils.js";

//meta info
var user = "user";// 表格名称
var columnsAttr = "Columns";// 列
var dataAttr = "Data";// 数据
var selectionAttr = "Selection";// 选中
var dlgVisibleAttr = "DlgVisible";// 对话框
var formAttr = "Form";
var recordAttr = "Record";// 表单模型
var rulesAttr = "Rules";// 表单验证
var curPageAttr = "CurrentPage";// 分页-当前页
var totalNumAttr = "TotalNum";// 分页-总数
var qParamAttr = "QueryParams";// 查询参数

// 用户信息-列
var userColumns = [{
  prop:"sslx",
  label:"用户所属类型"
},{
  prop: "sslxbh",
  label: "所属类型编号(工号/学号)",
  rules: [{
    required: true,
    message: "请输入姓名",
    trigger: "blur"
  }]
},{
  prop:"yhm",
  label:"用户名",
  rules: [{
    required: true,
    message: "请输入用户名",
    trigger: "blur"
  }]
},{
  prop: "sfqy",
  label: "是否启用",
  type: "boolean",
  width: 80,
  outOfSearch: true,
  align: "center",
  headerAlign: "center",
  renderer: trueFalseRenderer
}];


export default {
  components:{
    "table-panel": TablePanel
  },
  methods:{
    onSearching: function(tname, params) {
      var me = this;
      let url = "/jcYhxxb";// /static/data/system/user.json

      if(url !== "") {
        me[tname+qParamAttr] = {};
        me[tname+qParamAttr] = params;
        if (params.isAccurate) {
          me[tname+qParamAttr] = params.paramPairs;
        } else {
          me[tname+qParamAttr].keywords = params.query;
        }
        me.getRequest(url, me[tname+qParamAttr]).then(resp => {
            if(resp.status == 200) {
              me[tname+dataAttr] = resp.data.results;
              me[tname+totalNumAttr] = resp.data.total;
            }
        });
      }

    },
    onCreate: function(tname) {// 新增
      var me = this;
      me[tname+recordAttr] = formModelInitFromTable(me[tname+columnsAttr]);
      me[tname+recordAttr].yxf = true;// 创建时，有效否是选中的

      me[tname+dlgVisibleAttr] = true;
    },
    onEdit: function(tname, row) {// 编辑
      var me = this;
      me[tname + recordAttr]= row;
      me[tname + dlgVisibleAttr] = true;
    },
    onDelete: function(tname, row) {// 删除
      var me = this;
      me.$confirm("确定删除这条记录吗?", "提示", {
        type: "warning"
      }).then(() => {
        //TODO 发送请求，删除对应记录，显示删除结果，并重新查询表格
        // row就是本行数据
        me.$message({
          type: "success",
          message: "删除成功!"
        });
        //TODO 重新加载表格信息
      }).catch(() => {});
    },
    onExport: function(tname, params) {// 导出
      var me = this;
      me.$message({
        type: "info",
        message: "发送导出请求，返回下载路径"
      });
    },
    onSelectionChange: function(tname, data) {// 选中改变
      var me = this;
      // 缓存记录，按照角色编号，查询对应的选中权限节点数组
      me[tname+selectionAttr] = data;
    },
    onConfirm:function() {// 对话框-确认
      var me = this;
      // 验证信息
      var ret;
      me.$refs[user + formAttr].validate((result, what)=>{
        ret = result;
      });
      if(!ret){
        me.$message({
          message: "表单信息有误",
          type: "error"
        });
        return;
      }
      // 发送请求
      me.getRequest("/static/data/testSuc.json").then((resp)=>{
        if (resp.status == 200) {
          me.$message({
            message: "提交成功！"+ resp.data.msg,
            type: "success"
          });
          //最后，隐藏对话框
          me[user + dlgVisibleAttr] = false;
        } else {
          me.$message({
            message: "服务器发生错误，代码：" + resp.status,
            type: "error"
          });
        }
      });

    },
    onResetPassword:function() {// 只有在修改的时候会出现
      var me = this;
      var user = me[user + selection][0];

      me.$confirm("确定要重置用户"+user.xm+", "+user.yhm+"的密码吗？", "提示", {
        type: "warning"
      }).then(() => {
        me.$message({
          type: "success",
          message: "重置成功!"
        });
        //TODO 重新加载表格信息
      }).catch(() => {});
    },
    onPageChange:function(tname, page){// 分页改变
      var me = this;
      let url = "/static/data/system/user.json";

      if(url !== ""){
        me[tname+curPageAttr] = page;
        me[tname+qParamAttr]["page"] = page;
        me.getRequest(url, me[tname+qParamAttr]).then(resp => {
            if(resp.status == 200) {
              me[tname+dataAttr] = resp.data.results;
              me[tname+totalNumAttr] = resp.data.total;
            }
        });
      }

    },
    sslxChange:function(value){// 所属类型-改变
      //
      var me = this;
      var url = "/static/data/system/renyuan.json";//请求教师或者学生的列表，只需要姓名和工号/学号字段
      me.getRequest(url, {
        sslx: value//所属类型
      }).then(resp => {
          if(resp.status == 200) {
            me.teacherAndStudentData = resp.data.results;
          }
      });
    },
    sslxbhSearching:function(query){// 所属类型编号-远程搜索
      var me = this;
      if (query !== '') {
        me.sslxbhLoading = true;
        let url = "/static/data/system/renyuan.json";
        me.getRequest(url, {
          sslx: me[user+recordAttr].sslx,//所属类型
          query:query// 查询参数-通过后端保证查询上来的一定是包含这个关键字的，这里包含sslxbh和xm两个
        }).then(resp => {
            if(resp.status == 200) {
              me.teacherAndStudentData = resp.data.results;
              me.sslxbhLoading = false;
            }
        });
      } else {
        me.teacherAndStudentData = [];
      }
    }
  },
  data(){
    return {
      authorities:{
        create:true,
        delete:true,
        edit:true,
        search:true
      },// 权限控制
      [user+columnsAttr]: userColumns,// 表格-列
      [user+dataAttr]: [],// 表格的数据
      [user+selectionAttr]:[],// 当前选中
      [user+dlgVisibleAttr]:false,// 对话框是否可见
      [user+recordAttr]:{},// 表单模型
      [user+rulesAttr]:{},// 表单验证
      [user+curPageAttr]:1,
      [user+totalNumAttr]:0,
      [user+qParamAttr]:{},
      pageSize:20,// 每页数量
      teacherAndStudentData:[],
      sslxbhLoading:false
    };
  },
  created: function() {
    var me = this;
    // 添加权限控制
    // me.authorities = me.$route.meta.authorities;

    // 表单模型初始化
    me[user+recordAttr] = formModelInitFromTable(me[user+columnsAttr]);
    // 表单验证初始化
    me[user+rulesAttr] = formRulesInitFromTable(me[user+columnsAttr]);

    me.onSearching(user,{});
  }
}
</script>
<style lang="scss">

.components-system-user{
  height:100%;
}

</style>
